import React, { Component } from "react";
import { connect } from "dva";
import { Row, Col, Card, /* Tabs, List,  */Select, /* Radio,  */Spin, Badge } from "antd";
import moment from "moment";
import numeral from "numeral";
import { MiniArea } from "../../../components/Charts";

import DateComponent from "./components/dateComponent";
import ChartCard from "./components/ChartCard";
import { getTimeDistance } from "../../../utils/utils";
import StackedBar from "./components/StackedBar";

import {getSendData, getMsgSourceList, getTrendData} from "../services/statisticsApi";

import styles from "./SMSstatistics.less";

const { Option } = Select;
const topColResponsiveProps = {
  xs: 24,
  sm: 12,
  md: 12,
  lg: 12,
  xl: 6,
  style: { /* marginBottom: 7 */ }
};

const dafaultDate = getTimeDistance("date", 15);

@connect(({ chart }) => ({
  chart
}))
export default class SMSstatistics extends Component {
  state = {
    loading: false, // 统计loading
    barLoading: false,
    startDate: dafaultDate[0]
      ? moment(dafaultDate[0]).format("YYYY-MM-DD 00:00:00")
      : "",
    endDate: dafaultDate[0]
      ? moment(dafaultDate[1]).format("YYYY-MM-DD 23:59:59")
      : "",
    mode: "date",
    otherCount: { },
    pushData:[],
    pushDepList:[],
    butnvalue: '1',
    msgId: '',
    failCount: 0,
    successCount: 0,
    rate: 0,
  };

  componentDidMount() {
    const { dispatch } = this.props;
     this.setState(
      {
        loading: true,
        barLoading: true
      },
    ); 
    dispatch({
      type: "home/fetchTop4Count",
      payload: {}
    }).then(() => {
      this.setState({
        /* loading: false */
      });
    });
    dispatch({
      type: "chart/fetch"
    });
    getSendData().then(res => {if (res.success) this.setState({otherCount : res.datas,loading: false});
    });
    getMsgSourceList().then(res => {if (res.success) this.setState({pushDepList : res.datas,barLoading:false});
    });
    this.getTrendListData();
  }

  handleDateChange = (obj = {}) => {
    this.setState(
      {
        startDate: obj.date ? obj.date[0] : "",
        endDate: obj.date ? obj.date[1] : "",
        butnvalue: '4'
      },
      ()=>{this.getTrendListData();}
    );
  };

  handleSelect = value => {
    this.setState(
      {
        msgId: value
      },
      () => {this.getTrendListData();}
    );
  };

  getTrendListData = async () => {
    const res = await getTrendData({ 
      queryType: this.state.butnvalue, 
      msgSourceId:this.state.msgId, 
      beginTime:moment(this.state.startDate).format("YYYY-MM-DD"), 
      endTime: moment(this.state.endDate).format("YYYY-MM-DD")
    });
    if (res.success) {
      this.setState({
        pushData : res.datas.smsTrends,
        rate:res.datas.rate,
        failCount:res.datas.failCount,
        successCount:res.datas.successCount,
        barLoading:false,
      });
    };
  }

  render() {
    const {
      loading,
      barLoading,
      startDate,
      endDate,
      rate,
      failCount,
      successCount,
    } = this.state;
    const {
      chart 
    } = this.props;
    let pushList = [...this.state.pushData];
    // pushList = pushList.slice(0, 15);
    pushList = pushList.map(item => ({
      x: item.dateTime,
      y1: item.success,
      y2: item.fail
    }));
    pushList.sort((a, b) => new Date(a.x) - new Date(b.x));
    // 数据源
    const {
      cumulativeCount = 0,
      yearCount = 0,
      monthCount = 0,
    } = this.state.otherCount;
    
    const { visitData3, visitData4 } = chart;
    const handleSetStates = newValue => {
      this.setState({ butnvalue: newValue },
        () => {this.getTrendListData();}
      );
    };
    
    return (
      <div className={styles.root}>
        <div className={styles.up}>
          <Row gutter={24}>
            <Col {...topColResponsiveProps} >
              <ChartCard
                bordered={true}
                title={<Badge color="#108ee9" text="累计推送量" />}
                loading={loading}
                total={numeral(cumulativeCount).format("0,0")}
                contentHeight={20}
              >
                <MiniArea color="l (90) 0:rgba(0, 100, 205, 0.5) 1:rgba(0, 100, 205, 0)" 
                  borderColor = "rgba(0, 100, 205, 0.5)" 
                  line="true" 
                  data={visitData3}
                  padding = {[30,10, 50, 170]}
                  height={60}
                />
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps} offset={2}>
              <ChartCard
                bordered={true}
                title={<Badge color="#f50" text="今年推送量" />}
                loading={loading}
                total={numeral(yearCount).format("0,0")}
                contentHeight={20}
              >
                <MiniArea color="l (90) 0:rgba(255,100,97, 0.5) 1:rgba(255,100,97, 0)" 
                  borderColor = "rgba(255,100,97, 0.5)" 
                  line="true" 
                  data={visitData4}
                  padding = {[30,10, 50, 170]}
                  height={60}
                />
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps} offset={2}>
              <ChartCard
                bordered={true}
                title={<Badge color="#108ee9" text="本月推送量" />}
                loading={loading}
                total={numeral(monthCount).format("0,0")}
                contentHeight={20}
              >
                <MiniArea color="l (90) 0:rgba(0, 100, 205, 0.5) 1:rgba(0, 100, 205, 0)" 
                  borderColor = "rgba(0, 100, 205, 0.5)" 
                  line="true" 
                  data={visitData3}
                  padding = {[30,10, 50, 170]}
                  height={60}
                />
              </ChartCard>
            </Col>
          </Row>
        </div>
        <div className={styles.center}>
          <br/>
        </div>
        <div className={styles.down}>
          <Card
            title = {
              <div>
                <Row className={styles.cardTitle} >
                  <Col span={6}>
                    <span className={styles.txt}>消息源：</span>
                    <Select
                      className={styles.selectDep}
                      onChange={this.handleSelect}
                      allowClear={true}
                      placeholder="全部消息源"
                    >
                      {this.state.pushDepList.length > 0 ? (
                        this.state.pushDepList.map(({ msgSourceId, sourceName, sourceId }) => (
                          <Option key={msgSourceId} value={sourceId}>
                            {sourceName}
                          </Option>
                        ))
                      ) : (
                        <Option key="empty" disabled>
                          暂无数据！
                        </Option>
                      )}
                    </Select>
                  </Col>
                  <Col span={18}>
                    <DateComponent
                      handleSetStates={handleSetStates}
                      onChange={obj => this.handleDateChange(obj)}
                      getTrendListData={this.getTrendListData}
                    />
                  </Col>
                </Row>
              </div>
              
            }
            bordered={false}
            bodyStyle={{ padding: 0, overflow: "hidden" }}
          >
            <Spin spinning={barLoading}>
              <div className={styles.pushCard}>
                <StackedBar
                  data={pushList || []}
                  titleMap={{ y1: "成功量", y2: "失败量" }}
                  height={340}
                  failCount={failCount}
                  successCount={successCount}
                  rate={rate}
                  key={`${startDate}${endDate}`}
                />
              </div>
            </Spin>
          </Card>
        </div>
        
      </div>
    );
  }
}